package dao;

import bean.Goods;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.MyDataSource;

import java.sql.SQLException;
import java.util.List;

public class GoodsDao {
    //这里是对数据库中goods表进行增删改查
    public static boolean addGoods(Goods goods) throws SQLException {
        QueryRunner runner=new QueryRunner(MyDataSource.getDataSource());
        String sql="insert into goods(id,name,price,count) value(?,?,?,?)";
        int num=runner.update(sql,new Object[] {goods.getId(),goods.getName(),goods.getPrice(),goods.getCount()});
        if(num>0)
            return true;
        else
            return false;
    }

    public static boolean delGoods(String id) throws SQLException{
        QueryRunner runner=new QueryRunner(MyDataSource.getDataSource());
        String sql="delete from goods where id=?";
        int num=runner.update(sql,id);
        if(num>0)
            return true;
        else
            return false;
    }

    public  static boolean editGoods(Goods goods) throws SQLException{
        QueryRunner runner=new QueryRunner(MyDataSource.getDataSource());
        String sql="update goods set count=?,name=?,price=? where id=?";
        int num=runner.update(sql,new Object[]{goods.getCount(),goods.getName(),goods.getPrice(),goods.getId()});
        if(num>0)
            return true;
        else
            return false;
    }

    public static Goods findById(String id) throws SQLException{
        QueryRunner runner=new QueryRunner(MyDataSource.getDataSource());
        String sql="select * from goods where id=?";
        Goods goods=(Goods) runner.query(sql,new BeanHandler(Goods.class),new Object[] {id});
        return goods;
    }
    //模糊查询
    public static List<Goods> findByName(String name) throws SQLException{
        QueryRunner runner=new QueryRunner(MyDataSource.getDataSource());
        String sql="select * from goods where name like ?";//?赋值为'name%'
        List<Goods> goodsList=(List) runner.query(sql,new BeanListHandler(Goods.class),new Object[] {name+"%"});
        return goodsList;
    }

    //获取所有记录
    public static List<Goods> findAll() throws SQLException{
        QueryRunner runner=new QueryRunner(MyDataSource.getDataSource());
        String sql="select * from goods";
        List<Goods> goodsList=(List) runner.query(sql,new BeanListHandler(Goods.class));
        return goodsList;
    }
}
